﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace PMCSerialTransfer.Packets
{
    class ReqDataPacket :APacket
    {
         public override bool Packet(byte[] Data)
        {
            return Process(Data);
        }

         public override bool EndProcess(bool Ok)
         {
             int len;
             byte[] Data;
             if (Ok)
             {
                 if (Globals.DataPacket[0] != (byte)Globals.ACKType.E_ABORT)
                 {
                     if (Globals.DataPacket[0] != (byte)Globals.ACKType.E_ACK)
                     {
                         Globals.FilePtr -= (int)Globals.PacketSize - 4;
                         Globals.FileStream.Seek((long)Globals.FilePtr, 0);
                         Globals.Message = "\nCRC error... retrying\n.";
                     }
                     else
                     {
                         Globals.Message = ".";
                     }
                     if (Globals.FileLen - Globals.FilePtr > 128)
                         len = 128;
                     else
                         len = Globals.FileLen - Globals.FilePtr;
                     Data = new byte[len];
                     Globals.FileStream.Read(Data, 0, Data.Length);
                     //Data[0] = (byte)Globals.ACKType.E_ACK;

                     Globals.Create((byte)CommFactory.Command.SndACK, Data);
                     Globals.PacketSize = Data.Length;
                     Globals.FilePtr += len;
                     Globals.ProgressEvent = Globals.ProgressType.Add;
                     if (Globals.FilePtr >= Globals.FileLen)
                     {
                         Globals.FileStream.Close();
                         Globals.Message += "\nFile Sent\n";
                         Globals.ProgressEvent = Globals.ProgressType.Clear;
                         Globals.FilePtr = 0;
                     }
                 }
                 else
                 {

                     Globals.Message = "\nTransmission error... aborting\n";
                     Globals.FileStream.Close();
                     Globals.DataPacket = new byte[1];
                     Globals.DataPacket[0] = (byte)Globals.ACKType.E_ABORT;
                     Globals.Create((byte)CommFactory.Command.Abort, Globals.DataPacket);
                     Globals.ProgressEvent = Globals.ProgressType.Clear;
                 }
             }
          
             return Ok;
         }
    }
}
